package com.example.sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.config.ResponseBean;
import com.example.config.UnicomResponseEnums;
import com.example.sys.entity.Menu;
import com.example.sys.entity.RoleMenu;
import com.example.sys.service.MenuService;
import com.example.sys.service.RoleMenuService;
import com.example.sys.service.RoleService;
import com.example.sys.vo.MenuVo;
import com.example.util.HutoolUtils;
import org.apache.ibatis.io.ResolverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色和菜单关联表 前端控制器
 * </p>
 *
 * @author anan
 * @since 2019-08-29
 */
@RestController
@RequestMapping("/sys/role-menu")
public class RoleMenuController {

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RoleService roleService;


    /**
     * 根据前端传回角色ID，菜单,修改数据库sys_role_menu
     * @param map1
     * @return
     */
    @PostMapping("/updateRoleToMenu")
    public ResponseBean<UnicomResponseEnums> updateRoleToMenu(@RequestBody Map<String, Object> map1){
        HutoolUtils hutoolUtils = new HutoolUtils();
//      获取参数
        ArrayList<Object> arrayList = (ArrayList<Object>) map1.get("data");
        Long roleId = ((Integer) map1.get("roleId")).longValue();
        List<RoleMenu> roleMenuList = new ArrayList<>();
        RoleMenu roleMenu;
        Long menuId;
        Long parentId;
        List<Long> menuList = new ArrayList<>();
        List<Long> parentList = new ArrayList<>();
        if (arrayList.size() > 0) {
            for (int i = 0; i < arrayList.size(); i++) {
                Map<String, Object> map = (Map<String, Object>) arrayList.get(i);
                menuId = ((Integer) map.get("menuId")).longValue();
                menuList.add(menuId);
                parentId=((Integer) map.get("parentId")).longValue();
                if (parentId>0L)
                    parentList.add(parentId);
            }
        }
//        查询出全部菜单ID
        ergodicMenuId(menuList, parentList);
        menuList=hutoolUtils.mergeList(menuList);

        for (Long aLong : menuList) {
            roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(aLong);
            roleMenuList.add(roleMenu);
        }
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        roleMenuService.remove(wrapper);
        roleMenuService.saveBatch(roleMenuList);

        List<Menu> list=menuService.selectRoleKey();
        for (Menu menu : list) {
            menuService.updateById(menu);
        }

        return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
    }

    /**
     * 遍历全部菜单
     * @param list 回传list
     * @param parentIdList 父菜单ID
     */
    private void ergodicMenuId(List<Long> list,List<Long> parentIdList){
        List<Menu> menuList = new ArrayList<>();
        List<Long> listLong = new ArrayList<>();
        if (parentIdList.size() > 0) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.in("menu_id",parentIdList);
            menuList=menuService.list(queryWrapper);
        }
        for (Menu menu : menuList) {
            list.add(menu.getMenuId());
            if (menu.getParentId()>0L)
                listLong.add(menu.getParentId());
        }
        if (listLong.size()>0)
            ergodicMenuId(list, listLong);
    }


    /**
     * 将权限修的菜单
     *
     * @param map1 参考 map1:{data:data,roleId:roleId}
     * @return
     */
    @PostMapping("/updateRoleToMenu1")
    public ResponseBean<UnicomResponseEnums> updateRoleToMenu1(@RequestBody Map<String, Object> map1) {
//      工具类
        HutoolUtils hutoolUtils = new HutoolUtils();
//      获取参数
        ArrayList<Object> arrayList = (ArrayList<Object>) map1.get("data");
        Long roleId = ((Integer) map1.get("roleId")).longValue();
//      获取权限用户名
        String str = roleService.getById(roleId).getRoleKey();
//        删除前端权限组
        hutoolUtils.deleteRole(str);

        List<RoleMenu> list = new ArrayList<>();

        if (arrayList.size() > 0) {
            //      定义参数
            Long menuId;
            RoleMenu roleMenu;
            List<Long> list1 = new ArrayList<>();
            List<Long> list3 = new ArrayList<>();
            List<Menu> list2;
            List<Menu> list4;

//        遍历权限以及父菜单ID
            for (int i = 0; i < arrayList.size(); i++) {
                roleMenu = new RoleMenu();
                Map<String, Object> map = (Map<String, Object>) arrayList.get(i);
                menuId = ((Integer) map.get("menuId")).longValue();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                list.add(roleMenu);
                Long parentId = ((Integer) map.get("parentId")).longValue();
                list1.add(parentId);
            }
//        合并父菜单ID
            list1 = hutoolUtils.mergeList(list1);
//        获取菜单List
            QueryWrapper wrapper1 = new QueryWrapper();
            wrapper1.in("menu_id", list1);
            wrapper1.notIn("menu_type", "F");
            list2 = menuService.list(wrapper1);


//        修改前端权限菜单（菜单）
            for (Menu menu : list2) {
                list3.add(menu.getParentId());
                // M目录 C菜单 F按钮
                if (menu.getMenuType().equals("C")) {   //菜单
                    hutoolUtils.setRole(menu.getUrl(), str);
                }
            }
            list3 = hutoolUtils.mergeList(list3);
            QueryWrapper wrapper2 = new QueryWrapper();
            wrapper2.in("menu_id", list3);
            wrapper2.notIn("menu_type", "C");
            list4 = menuService.list(wrapper2);
            //        修改前端权限菜单（目录）
            for (Menu menu : list4) {
                // M目录 C菜单 F按钮
                if (menu.getMenuType().equals("M")) {   //菜单
                    hutoolUtils.setRole(menu.getUrl(), str);
                }
            }
        }
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        roleMenuService.remove(wrapper);
        roleMenuService.saveBatch(list);


        return new ResponseBean(true, UnicomResponseEnums.SUCCESS_OPTION);
    }

}
